package com.fw.leetcode.slidingwindow;

import com.fw.leetcode.LeetCode;

import java.util.HashSet;

/**
 * 219. Contains Duplicate II
 *
 * Given an integer array nums and an integer k, return true if there are two distinct indices i and j in
 * the array such that nums[i] == nums[j] and abs(i - j) <= k.
 *
 * Example 1:
 *  Input: nums = [1,2,3,1], k = 3
 *  Output: true
 *
 * Example 2:
 *  Input: nums = [1,0,1,1], k = 1
 *  Output: true
 *
 * Example 3:
 *  Input: nums = [1,2,3,1,2,3], k = 2
 *  Output: false
 *
 * Constraints:
 *  1 <= nums.length <= 10^5
 *  -10^9 <= nums[i] <= 10^9
 *  0 <= k <= 10^5
 */
public class Num_0219 implements LeetCode {
    private interface Solution {
        boolean containsNearbyDuplicate(int[] nums, int k);

        default void assertEquals(int[] nums, int k, boolean expected) {
            if (containsNearbyDuplicate(nums, k) != expected) {
                containsNearbyDuplicate(nums, k);
            }
        }
    }

    private static class MySolution implements Solution {

        @Override
        public boolean containsNearbyDuplicate(int[] nums, int k) { // 哈希集合 + 滑动窗口：时O(n) 空O(k)
            /*
             * 存在重复元素 II (k间距内)
             * 哈希集合 + 滑动窗口
             * - k 是窗口最大间距，实际窗口大小为 k+1
             * [0,1,2,3,4] k=2 时，窗口大小 3
             */
            HashSet<Integer> set = new HashSet<>();
            for (int i = 0; i < nums.length; i++) {
                if (i > k) { // 超出第一个窗口时，窗口每后移一次，都需头出一个，尾入一个
                    set.remove(nums[i-k-1]); // 去头
                }
                if (set.contains(nums[i])) { // 尾入的元素在窗口中已存在则返回结束 true
                    return true;
                }
                set.add(nums[i]); // 否则加入哈希集合
            }
            return false;
        }
    }

    public static void main(String[] args) {
        Solution solution = new MySolution();
        solution.assertEquals(new int[]{1,2,3,1}, 3, true);
        solution.assertEquals(new int[]{1,0,1,1}, 1, true);
        solution.assertEquals(new int[]{1,2,3,1,2,3}, 2, false);
    }
}
